//
//  Util.swift
//  GitOSC-Swift
//
//  Created by 李萍 on 16/1/4.
//  Copyright © 2016年 李萍. All rights reserved.
//

import UIKit
import SwiftyJSON

enum EventAction: Int {
    case EventActionCreated = 1
    case EventActionUpdated
    case EventActionClosed
    case EventActionReopened
    case EventActionPushed
    case EventActionCommented
    case EventActionMerged
    case EventActionJoined
    case EventActionLeft = 9
    case EventActionForked = 11
}

class Util: NSObject {
    func getEventDescription(event: GTEvent) -> String {
        var eventTitle = ""
        let authorName = JSON((event.author?.name)!)
        let projectOwnerName = JSON((event.project?.owner?.name)!)
        let projectName = JSON((event.project?.name)!)
        
        if let action = EventAction(rawValue: event.action!) {
            switch action {
            case .EventActionCreated :
                eventTitle = "\(authorName)"+" 在项目 "+"\(projectOwnerName)"+"/"+"\(projectName)"+" 创建了 "+"\(self.getEventTitle(event))"

            case .EventActionUpdated:
                eventTitle = "\(authorName)"+" 更新了动态 "

            case .EventActionClosed :
                eventTitle = "\(authorName)"+" 关闭了项目 "+"\(projectOwnerName)"+"/"+"\(projectName)"+"\(self.getEventTitle(event))"

            case .EventActionReopened :
                eventTitle = "\(authorName)"+" 重新打开了项目 "+"\(projectOwnerName)"+"/"+"\(projectName) 的"+"\(self.getEventTitle(event))"

            case .EventActionPushed :
                let lastPaths = (JSON(event.data!)["ref"].stringValue).componentsSeparatedByString("/")
                let lastPath = lastPaths.last
                eventTitle = "\(authorName)"+"  推送到了项目  "+"\(projectOwnerName)"+"/"+"\(projectName) 的 "+"\(lastPath)"+" 的分支"

            case .EventActionCommented :
                eventTitle = "\(authorName)"+" 发表了项目 "+"\(projectOwnerName)"+"/"+"\(projectName)"+" 的评论"

            case .EventActionMerged :
                eventTitle = "\(authorName)"+" 接受了项目 "+"\(projectOwnerName)"+"/"+"\(projectName) 的"+"\(self.getEventTitle(event))"

            case .EventActionJoined :
                eventTitle = "\(authorName)"+" 加入了项目 "+"\(projectOwnerName)"+"/"+"\(projectName)"

            case .EventActionLeft :
                eventTitle = "\(authorName)"+" 离开了项目 "+"\(projectOwnerName)"+"/"+"\(projectName)"

            case .EventActionForked :
                eventTitle = "\(authorName)"+" fork了项目 "+"\(projectOwnerName)"+"/"+"\(projectName)"

            }
        }
        return eventTitle
    }
    
    func getEventTitle(event:GTEvent) -> String {
        var eventTitle = ""
        let json = JSON(event.events!)
        if json["pull_request"].count > 0 {
            let iid = json["pull_request"]["iid"]
            eventTitle = "Pull Request #\(iid)"
        } else if json["issue"].count > 0 {
            let iid = json["issue"]["iid"]
            eventTitle = "Issue #\(iid)"
        } else {
            eventTitle = " "
        }
        return eventTitle
    }
    
    func getEventContent(event:GTEvent) -> String {
        var eventTitle = ""
        let json = JSON(event.events!)
        if json["pull_request"].count > 0 {
            eventTitle = json["pull_request"]["title"].stringValue
        } else if json["issue"].count > 0 {
            eventTitle = json["issue"]["title"].stringValue
        } else {
            eventTitle = " "
        }
        
        return eventTitle
    }
    
    func getEventContentView(contentLabel: UILabel, event: GTEvent) -> String {
        var totalCommits = 0
        let jsonEvent = JSON(event.events!)
        var labelText = ""
        
        let action = EventAction(rawValue: event.action!)
        
        if ((event.data?.isEmpty) != nil) {
            if event.data!.count > 0 {
                let jsonData = JSON(event.data!)
                totalCommits = jsonData["total_commits_count"].intValue
            }
        }
        
        
        if totalCommits > 0 {
            contentLabel.backgroundColor = UIColor.lightGrayColor()
            labelText = self.getEventContentLabel(event)
            contentLabel.text = labelText
        } else if action == EventAction.EventActionCommented {
            contentLabel.backgroundColor = UIColor.lightGrayColor()
            var comment = jsonEvent["note"]["note"].stringValue
            
            if comment.isEmpty {
                comment = " "
            }
            labelText = comment
            contentLabel.text = labelText
            
        } else if action == EventAction.EventActionMerged {
            contentLabel.backgroundColor = UIColor.lightGrayColor()
            labelText = self.getEventContent(event)
            contentLabel.text = labelText
            
        } else if action == EventAction.EventActionCreated {
            contentLabel.backgroundColor = UIColor.lightGrayColor()
            var eventTitle = ""

            if event.targetType == "PullRequest" {
                eventTitle = jsonEvent["pull_request"]["title"].stringValue
            } else if event.targetType == "Issue" {
                eventTitle = jsonEvent["issue"]["title"].stringValue
            }
            labelText = eventTitle
            contentLabel.text = labelText
        } else {
            contentLabel.backgroundColor = UIColor.whiteColor()
            labelText = ""
            contentLabel.text = ""
        }
        
        return labelText
    }
    
    func getEventContentLabel(event: GTEvent) -> String {
        var contentString = ""
        let json = JSON(event.data!)
        let totalCommits = json["total_commits_count"].intValue
        var digests = 0
        
        while totalCommits > 0 {
            var commitId = json["commits"][digests]["id"].stringValue
            commitId = commitId.substringToIndex(commitId.startIndex.advancedBy(9))
            
            let message = json["commits"][digests]["message"].stringValue
            let commitAuthorName = json["commits"][digests]["author"]["name"].stringValue
            contentString = "\(commitId)\(commitAuthorName) - \(message)"
            
            if ++digests == totalCommits || digests >= 2 {break}
            
        }
        
        if totalCommits > 2 {
            let moreCommits = "\n ... and\(totalCommits - 2) more commits"
            
            contentString = "\(contentString)\(moreCommits)"
        }
        
        return contentString
    }
    
}
